//
//  UIImage+Extend.swift
//  UIImage
//
//  Created by mini on 2025/4/28.
//

import Foundation

extension UIImage {
    func crop(toPixelRect rect: CGRect) -> UIImage? {
        guard let cgImage = cgImage else { return nil }

        // 获取图像的 scale 值
        let scale = self.scale

        // 将像素区域转换为图像的坐标系统
        let pixelRect = CGRect(
            x: rect.origin.x * scale,
            y: rect.origin.y * scale,
            width: rect.size.width * scale,
            height: rect.size.height * scale
        )

        // 裁剪图像的像素区域
        guard let croppedCgImage = cgImage.cropping(to: pixelRect) else { return nil }

        // 返回裁剪后的图像
        return UIImage(cgImage: croppedCgImage, scale: scale, orientation: imageOrientation)
    }

    static func verticalMerge(images: [UIImage]) -> UIImage? {
        guard !images.isEmpty else { return nil }

        let padding: CGFloat = 10
        let horizontalPadding: CGFloat = 20 // 左右边距
        let cornerRadius: CGFloat = 16 // 新增圆角值
        let topTextPadding: CGFloat = 10 // 新增顶部文字上方间距
        let bottomTextPadding: CGFloat = 10 // 新增底部文字间距

        let lastGridImages = images.count >= 4 ? Array(images.suffix(4)) : []
        let normalImages = images.count >= 4 ? Array(images.prefix(images.count - 4)) : images

        // 计算尺寸
        var totalHeight: CGFloat = 0
        var maxWidth: CGFloat = 0

        // 添加顶部文字所需高度
        let topTextHeight: CGFloat = 30
        totalHeight += topTextHeight + topTextPadding + bottomTextPadding // 增加顶部和底部间距

        for image in normalImages {
            totalHeight += image.size.height + padding
            maxWidth = max(maxWidth, image.size.width)
        }

        if !lastGridImages.isEmpty {
            let gridWidth = maxWidth
            let gridItemWidth = (gridWidth - padding) / 2
            let gridItemHeight = gridItemWidth
            let gridRows = (lastGridImages.count + 1) / 2
            let gridHeight = CGFloat(gridRows) * gridItemHeight + CGFloat(gridRows - 1) * padding
            totalHeight += gridHeight
        }

        // 创建上下文
        UIGraphicsBeginImageContextWithOptions(CGSize(width: maxWidth, height: totalHeight), false, 0)

        // 绘制白色背景
        let backgroundPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: maxWidth, height: totalHeight), cornerRadius: cornerRadius)
        UIColor.white.setFill()
        backgroundPath.fill()

        // 绘制背景图
        if let bgImage = UIImage(named: "today_share_long") {
            let context = UIGraphicsGetCurrentContext()
            context?.saveGState()
            backgroundPath.addClip() // 使用相同的圆角路径作为裁剪区域
            bgImage.draw(in: CGRect(x: 0, y: 0, width: maxWidth, height: totalHeight))
            context?.restoreGState()
        }

        // 绘制顶部日期文字
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "zh_CN")
        dateFormatter.dateFormat = "今天，yyyy年M月d日 EEEE"
        let dateString = dateFormatter.string(from: Date())
        let textColor = UIColor(red: 0.094, green: 0.129, blue: 0.22, alpha: 1)
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont(name: "PingFangSC-Semibold", size: 15) ?? UIFont.systemFont(ofSize: 15),
            .foregroundColor: textColor,
        ]

        let textSize = dateString.size(withAttributes: attributes)
        let textX = (maxWidth - textSize.width) / 2
        let textRect = CGRect(x: textX, y: topTextPadding, width: textSize.width, height: topTextHeight)
        dateString.draw(in: textRect, withAttributes: attributes)

        var currentY: CGFloat = topTextHeight + topTextPadding + bottomTextPadding // 更新起始Y坐标，增加底部间距

        // 绘制普通图片
        for image in normalImages {
            // 调整图片大小以适应边距
            let availableWidth = maxWidth - horizontalPadding * 2
            let scale = availableWidth / image.size.width
            let scaledHeight = image.size.height * scale
            let scaledWidth = image.size.width * scale

            let x = horizontalPadding + (availableWidth - scaledWidth) / 2
            let rect = CGRect(x: x, y: currentY, width: scaledWidth, height: scaledHeight)
            image.draw(in: rect)
            currentY += scaledHeight + padding
        }

        // 绘制网格部分
        if !lastGridImages.isEmpty {
            let availableWidth = maxWidth - horizontalPadding * 2
            let gridItemWidth = (availableWidth - padding) / 2
            let gridItemHeight = gridItemWidth

            for (index, image) in lastGridImages.enumerated() {
                let row = index / 2
                let col = index % 2

                let x = horizontalPadding + CGFloat(col) * (gridItemWidth + padding)
                let y = currentY + CGFloat(row) * (gridItemHeight + padding)

                let rect = CGRect(x: x, y: y, width: gridItemWidth, height: gridItemHeight)
                image.draw(in: rect)
            }
        }

        let mergedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return mergedImage
    }
}
